package com.kelaite.procurement.service.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kelaite.procurement.dto.UnitDTO;
import com.kelaite.procurement.entity.TUnit;
import com.kelaite.procurement.repository.UnitRepository;
import com.kelaite.procurement.service.UnitService;
import com.kelaite.procurement.utils.ConvertUtil;

@Service
@Transactional
public class UnitServiceImpl implements UnitService {

	@Autowired
	private UnitRepository unitRepository;

	@PersistenceContext
	private EntityManager em;

	@Override
	public UnitDTO save(TUnit persistence) {
		return ConvertUtil.convertObj(unitRepository.save(persistence),
				UnitDTO.class);
	}

	@Override
	public UnitDTO getObject(Long id) {
		return ConvertUtil
				.convertObj(unitRepository.findOne(id), UnitDTO.class);
	}

	@Override
	public List<UnitDTO> getAll() {
		return ConvertUtil.convertList(unitRepository.findAll(), UnitDTO.class);
	}

	@Override
	public void deleteByObject(UnitDTO persistence) {
		this.unitRepository.delete(ConvertUtil.convertObj(persistence,
				TUnit.class));
	}

	@Override
	public void deleteByPrimaryKey(Long id) {
		this.unitRepository.delete(id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UnitDTO> getByProperty(String property, Object value) {
		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TUnit.class).add(
				Restrictions.eq(property, value));
		return ConvertUtil.convertList(criteria.list(), UnitDTO.class);
	}

}
